import router from '@/router'
import store from '@/store'
import { TOKEN } from '@/store/modules/app' // TOKEN变量名

const getPageTitle = title => {
    const appTitle = store.state.app.title
    if (title) {
        return `${title} - ${appTitle}`
    }
    return appTitle
}

const WhiteList = ['home','login','register','QQLogin']

router.beforeEach(async to => {
    document.title = getPageTitle(!!to.meta && to.meta.title)
    if (WhiteList.includes(to.name)) {
        return true
    }
    if (!window.localStorage[TOKEN]) {
        return {
            name: 'login',
            query: {
                redirect: to.fullPath, // redirect是指登录之后可以跳回到redirect指定的页面
            },
            replace: true,
        }
    } else {
        // 获取用户角色信息，根据角色判断权限
        let userinfo = store.state.users.userinfo
        if (!userinfo) {
            try {
                // 获取用户信息
                userinfo = await store.dispatch('users/getUserinfo')
            } catch (err) {
                return false
            }
        }
    }
})